const App = getApp();
Page({
  data: {
    authorStatus: false
  },
  onLoad: function (options) {},
  // 手机号码授权
  getPhoneNumber: function (e) {
    let that = this
    wx.checkSession({
      success() {
        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {

        } else {
          App.api.$http({
            url: 'user/get_phone',
            method: 'POST',
            data: {
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              usertoken: wx.getStorageSync('token'),
              user_id: wx.getStorageSync('user_id')
            }
          }, {
            showLoading: true,
          }).then(res => {
            wx.setStorageSync('phone', res.data.phone);
            that.setData({
              authorStatus: false
            })
            wx.navigateBack();
          })
        }
      }
    })
  },
  // 微信授权登录
  authorLogin: function (e) {
    let that = this;
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      return false;
    }
    wx.showLoading({
      title: "正在登录",
      mask: true
    });
    wx.setStorageSync("userInfo", e.detail.userInfo);
    wx.login({
      success: function (res) {
        let code = res.code;
        that.doLogin(e.detail, code);
      }
    });
  },
  // 登录
  async doLogin(e, code) {
    let that = this
    await App.api.$http({
      url: 'user/login',
      method: 'POST',
      data: {
        code: code,
        user_info: e.rawData,
        encrypted_data: e.encryptedData,
        iv: e.iv,
        signature: e.signature,
        referee_id: wx.getStorageSync('referee_id') || '',
      }
    }, {
      showLoading: true,
    }).then(res => {
      wx.setStorageSync('user_token', res.data.token);
      wx.setStorageSync('user_id', res.data.user_id);
      if(res.data.user_phone){
        wx.navigateBack()
      }
      that.setData({
        authorStatus: true
      })
    })
  },
  cancel_get: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * 授权成功 跳转回原页面
   */
  navigateBack: function () {
    wx.navigateBack();
  },

})